package cn.ljh.zard.listen.scan;

import cn.ljh.zard.listen.BaseListener;
import cn.ljh.zard.listen.scan.IAutoScanListener;
import org.reflections.Reflections;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;

/**
 * 自动扫描所有 实现了BaseListener接口的类
 */
public class AutoScanListener implements IAutoScanListener {


    public final static String baseScanDir = "cn.ljh";

    @Override
    public Collection<BaseListener> scan() {

        Collection<BaseListener> baseListeners = new ArrayList<>();

        Reflections scanRelections = new Reflections(baseScanDir);
        Set<Class<? extends BaseListener>> candidateClazz = scanRelections.getSubTypesOf(BaseListener.class);

        for (Class<? extends BaseListener> clazz : candidateClazz) {

            try {
                BaseListener e = clazz.newInstance();
                // 需要做一次init初始化方法
                e.init();
                baseListeners.add(e);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }


        }
        return baseListeners;


    }


}
